using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RevivePanel : BasePanel, IInitializable
{
    private int price = 100;
    private string from = "close";
    public void Initialize(object data)
    {
        Debug.Log("RevivePanel initialized" + data);
    }
    public void OnCloseClick()
    {
        // 关闭面板
        PanelManager.Instance.ClosePanel<RevivePanel>();
    }

    public override void OnOpen()
    {
        base.OnOpen(); // 调用基类的 OnOpen 方法
        GlobalEventManager.OnEvent("AdsPlaybackCompleted", OnAdsPlaybackCompleted);
        from = "close";
        // 在面板打开时执行的逻辑
        Debug.Log("RevivePanel opened");
        StartCoroutine(DelayShowNoThanks());
        AudioManager.Instance.PlaySoundEffect("sounds_failed");
    }

    public override void OnClose()
    {
        base.OnClose(); // 调用基类的 OnClose 方法
        GlobalEventManager.OffEvent("AdsPlaybackCompleted", OnAdsPlaybackCompleted);

        // 在面板关闭时执行的逻辑
        Debug.Log("RevivePanel closed");

        if (from == "close")
        {
            PanelManager.Instance.OpenPanel<FailedPanel>();
        }
    }

    private IEnumerator DelayShowNoThanks()
    {
        Transform tf = transform.Find("Bg/NoThanks");
        if (tf != null)
        {
            tf.gameObject.SetActive(false);
            yield return new WaitForSeconds(1f);
            tf.gameObject.SetActive(true);
        }
        else
        {
            Debug.LogError("NoThanks not found");
        }
    }

    public void OnBuyClick()
    {
        Debug.Log("Buy");
        float coins = (float)UserManager.Instance.GetUserInfo()["Coins"];
        if (coins < price)
        {
            Tools.ShowTipToast("Insufficient coins");
            return;
        }
        from = "buy";
        OnCloseClick();
        //复活
        GameManager.Instance.GameRevive();
    }

    public void OnWatchAdsClick()
    {
        // 点击了看广告按钮
        Debug.Log("WatchAds button clicked");
        bool st = AdsManager.Instance.IsRewardedAdReady();
        if (st)
        {
            AdsManager.Instance.ShowRewardedAd();
            from = "buy";
        }
        else
        {
            Tools.ShowTipToast("Ad is not Ready");
        }
    }

    public void OnAdsPlaybackCompleted()
    {
        Debug.Log("广告播放完成");

        from = "buy";
        OnCloseClick();
        GameManager.Instance.GameRevive();
    }
}
